package com.logictech.lims.web.api;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.jeecgframework.p3.core.web.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.util.StringUtils;
import com.logictech.activity.system.service.SystemUserService;
import com.logictech.activity.system.vo.LoginUser;
import com.logictech.common.util.SystemEnum;
import com.logictech.common.util.data.DateUtils;
import com.logictech.lims.dto.BarCodeReq;
import com.logictech.lims.dto.BarCodeResp;
import com.logictech.lims.dto.MovePositionReq;
import com.logictech.lims.dto.OpenReq;
import com.logictech.lims.dto.PreparationInventoryDto;
import com.logictech.lims.dto.ReagentInventoryDto;
import com.logictech.lims.entity.PreparationType;
import com.logictech.lims.entity.ReagentType;
import com.logictech.lims.service.PreparationInventoryService;
import com.logictech.lims.service.PreparationTypeService;
import com.logictech.lims.service.ReagentInventoryService;
import com.logictech.lims.service.ReagentTypeService;
import com.logictech.wechat.model.responseDto.JsonResp;

/**
 * 描述：</b>PreparationTypeController<br>
 * 
 * @author guoqi
 * @since：2017年03月21日 16时10分42秒 星期二
 * @version:1.0
 */
@Controller
@RequestMapping("/lims/api/barcode")
public class ApiBarCodeController extends BaseController {
	@Autowired
	private PreparationInventoryService preparationInventoryService;
	
	@Autowired
	private ReagentInventoryService reagentInventoryService;
	
	@Autowired
	private ReagentTypeService reagentTypeService;
	
	@Autowired
	private PreparationTypeService preparationTypeService;
	
	@Autowired
	private SystemUserService systemUserService;

	/**
	 * 获取试液或者试剂信息
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = { "/getBarCodeInfo" }, produces = "application/json",method = {org.springframework.web.bind.annotation.RequestMethod.GET,
			org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
    public JsonResp<BarCodeResp> getBarCodeInfo(@RequestBody BarCodeReq barCodeDto){
		String barCodeType = "";
		PreparationInventoryDto preparationInventoryDto = null;
		ReagentInventoryDto reagentInventoryDto = null;
		// 判断编码非空
		if(StringUtils.isEmpty(barCodeDto.getBarCode())){
			return new JsonResp<BarCodeResp>(SystemEnum.ARGUMENT_ERROR.getErrCode(),SystemEnum.ARGUMENT_ERROR.getErrChineseMsg());
		}
		
		if(barCodeDto.getBarCode().startsWith("01")){
			barCodeType="01";
			// 查询试剂
			reagentInventoryDto = this.reagentInventoryService.queryByNo(barCodeDto.getBarCode());
			if(reagentInventoryDto == null){
				return new JsonResp<BarCodeResp>(SystemEnum.DATA_NOT_EXIST_ERROR.getErrCode(),SystemEnum.DATA_NOT_EXIST_ERROR.getErrChineseMsg());
			}
		}else if(barCodeDto.getBarCode().startsWith("02")){
			barCodeType="02";
			// 查询试液
			preparationInventoryDto = this.preparationInventoryService.queryByNo(barCodeDto.getBarCode());
			if(preparationInventoryDto == null){
				return new JsonResp<BarCodeResp>(SystemEnum.DATA_NOT_EXIST_ERROR.getErrCode(),SystemEnum.DATA_NOT_EXIST_ERROR.getErrChineseMsg());
			}
		}
		BarCodeResp barCodeResp = new BarCodeResp();
		barCodeResp.setBarCodeType(barCodeType);
		barCodeResp.setPreparationInventoryDto(preparationInventoryDto);
		barCodeResp.setReagentInventoryDto(reagentInventoryDto);
        JsonResp<BarCodeResp> resp = new JsonResp<BarCodeResp>();
        resp.setInfo(barCodeResp);
        return resp;
    }
	
	/**
	 * 试液试剂移库
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = { "/movePosition" }, produces = "application/json",method = { org.springframework.web.bind.annotation.RequestMethod.GET,
			org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
    public JsonResp<String> movePosition(HttpServletRequest request, @RequestBody MovePositionReq movePositionReq){
		PreparationInventoryDto preparationInventoryDto = null;
		ReagentInventoryDto reagentInventoryDto = null;
		// 判断编码非空
		if(StringUtils.isEmpty(movePositionReq.getBarCode())){
			return new JsonResp<String>(SystemEnum.ARGUMENT_ERROR.getErrCode(),"条形码"+SystemEnum.ARGUMENT_ERROR.getErrChineseMsg());
		}
		
		// 判断用户id非空
		if(StringUtils.isEmpty(movePositionReq.getUserId())){
			return new JsonResp<String>(SystemEnum.ARGUMENT_ERROR.getErrCode(),"用户id"+SystemEnum.ARGUMENT_ERROR.getErrChineseMsg());
		}
		
		// 判断位置id非空
		if(StringUtils.isEmpty(movePositionReq.getPositionId())){
			return new JsonResp<String>(SystemEnum.ARGUMENT_ERROR.getErrCode(),"位置id"+SystemEnum.ARGUMENT_ERROR.getErrChineseMsg());
		}
		
		// 判断库位id非空
		if(StringUtils.isEmpty(movePositionReq.getLocationId())){
			return new JsonResp<String>(SystemEnum.ARGUMENT_ERROR.getErrCode(),"库位id"+SystemEnum.ARGUMENT_ERROR.getErrChineseMsg());
		}
		LoginUser user = this.systemUserService.queryUserByUserId(movePositionReq.getUserId());
		if(user != null){
			request.getSession().setAttribute("OPERATE_WEB_LOGIN_USER", user);
		}
		if(movePositionReq.getBarCode().startsWith("01")){
			// 查询试剂
			reagentInventoryDto = this.reagentInventoryService.queryByNo(movePositionReq.getBarCode());
			if(reagentInventoryDto == null){
				log.error("移库失败，试剂编号："+movePositionReq.getBarCode()+"，试剂库存表" + SystemEnum.DATA_NOT_EXIST_ERROR.getErrChineseMsg());
				return new JsonResp<String>(SystemEnum.OPERATION_ERROR.getErrCode(),SystemEnum.OPERATION_ERROR.getErrChineseMsg());
			}
			ReagentType reagentType = reagentTypeService.queryById(reagentInventoryDto.getReagentTypeId().toString());
			if(reagentType == null){
				log.error("移库失败，试剂类型id："+reagentInventoryDto.getReagentTypeId()+"，试剂类型表" + SystemEnum.DATA_NOT_EXIST_ERROR.getErrChineseMsg());
				return new JsonResp<String>(SystemEnum.OPERATION_ERROR.getErrCode(),SystemEnum.OPERATION_ERROR.getErrChineseMsg());
			}
			reagentType.setPositionId(Integer.parseInt(movePositionReq.getPositionId()));
			reagentType.setLocationId(Integer.parseInt(movePositionReq.getLocationId()));
			reagentType.setUpdateTime(new Date());
			reagentType.setUpdateUser(user.getId().toString()); 
			reagentTypeService.doEdit(reagentType);
		}else if(movePositionReq.getBarCode().startsWith("02")){
			// 查询试液
			preparationInventoryDto = this.preparationInventoryService.queryByNo(movePositionReq.getBarCode());
			if(preparationInventoryDto == null){
				log.error("移库失败，试液编号："+movePositionReq.getBarCode()+"，试液库存表" + SystemEnum.DATA_NOT_EXIST_ERROR.getErrChineseMsg());
				return new JsonResp<String>(SystemEnum.OPERATION_ERROR.getErrCode(),SystemEnum.OPERATION_ERROR.getErrChineseMsg());
			}
			PreparationType preparationType = preparationTypeService.queryById(preparationInventoryDto.getPreparationTypeId().toString());
			if(preparationType == null){
				log.error("移库失败，试液类型id："+preparationInventoryDto.getPreparationTypeId()+"，试液类型表" + SystemEnum.DATA_NOT_EXIST_ERROR.getErrChineseMsg());
				return new JsonResp<String>(SystemEnum.OPERATION_ERROR.getErrCode(),SystemEnum.OPERATION_ERROR.getErrChineseMsg());
			}
			preparationType.setPositionId(Integer.parseInt(movePositionReq.getPositionId()));
			preparationType.setLocationId(Integer.parseInt(movePositionReq.getLocationId()));
			preparationType.setUpdateTime(new Date());
			preparationType.setUpdateUser(user.getId().toString()); 
			preparationTypeService.doEdit(preparationType);
		}
		
        return new JsonResp<String>();
    }
	
	/**
	 * 试剂开瓶
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = { "/open" }, produces = "application/json",method = { org.springframework.web.bind.annotation.RequestMethod.GET,
			org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
    public JsonResp<String> open(HttpServletRequest request, @RequestBody OpenReq openReq){
		ReagentInventoryDto reagentInventoryDto = null;
		// 判断编码非空
		if(StringUtils.isEmpty(openReq.getBarCode())){
			return new JsonResp<String>(SystemEnum.ARGUMENT_ERROR.getErrCode(),"条形码"+SystemEnum.ARGUMENT_ERROR.getErrChineseMsg());
		}
		
		// 判断用户id非空
		if(StringUtils.isEmpty(openReq.getUserId())){
			return new JsonResp<String>(SystemEnum.ARGUMENT_ERROR.getErrCode(),"用户id"+SystemEnum.ARGUMENT_ERROR.getErrChineseMsg());
		}
		LoginUser user = this.systemUserService.queryUserByUserId(openReq.getUserId());
		if(user != null){
			request.getSession().setAttribute("OPERATE_WEB_LOGIN_USER", user);
		}
		if(openReq.getBarCode().startsWith("01")){
			// 查询试剂
			reagentInventoryDto = this.reagentInventoryService.queryByNo(openReq.getBarCode());
			if(reagentInventoryDto == null){
				log.error("开启失败，试剂编号："+openReq.getBarCode()+"，试剂库存表" + SystemEnum.DATA_NOT_EXIST_ERROR.getErrChineseMsg());
				return new JsonResp<String>(SystemEnum.OPERATION_ERROR.getErrCode(), SystemEnum.OPERATION_ERROR.getErrChineseMsg());
			}
			
			if(!"0".equals(reagentInventoryDto.getStatus())){
				log.error("开启失败，试剂编号："+openReq.getBarCode()+"，试剂状态有误");
				return new JsonResp<String>(SystemEnum.OPERATION_ERROR.getErrCode(), SystemEnum.OPERATION_ERROR.getErrChineseMsg());
			}
			
			// 检查是否已经过期
			if(DateUtils.checkDateCompare(reagentInventoryDto.getEffectiveDate(), DateUtils.getCurrentDateString(), DateUtils.COMPARE_TYPE_GT, DateUtils.PATTEN_YMD)){
				return new JsonResp<String>(SystemEnum.OPERATION_ERROR.getErrCode(), "该试剂已过期，无法开启！");
			}
			
			// 2017-08-18 取消以下处理
			// 查询有效日期最小的试剂
			//ReagentInventoryDto minEffectiveDateReagentInventoryDto = reagentInventoryService.getMinEffectiveDate(reagentInventoryDto.getReagentTypeId());
			
			//if(DateUtils.checkDateCompare(minEffectiveDateReagentInventoryDto.getEffectiveDate(), reagentInventoryDto.getEffectiveDate(), DateUtils.COMPARE_TYPE_GT, DateUtils.PATTEN_YMD)){
			//	return new JsonResp<String>(SystemEnum.OPERATION_ERROR.getErrCode(), "请开启有效日期最近的试剂【"+reagentInventoryDto.getBarCode()+"】");
			//}
			
			reagentInventoryDto.setOpener(user.getId().toString());
			reagentInventoryDto.setOpenDate(DateUtils.dateToString(DateUtils.PATTEN_YMD));
			reagentInventoryDto.setStatus("1");
			reagentInventoryDto.setUpdateTime(new Date());
			reagentInventoryDto.setUpdateUser(openReq.getUserId());
			reagentInventoryService.doEdit(reagentInventoryDto);
		}else{
			return new JsonResp<String>(SystemEnum.ARGUMENT_ERROR.getErrCode(),"试剂条形码" + SystemEnum.ARGUMENT_ERROR.getErrChineseMsg());
		}
		
        return new JsonResp<String>();
    }
	
	/**
	 * 试液试剂使用完毕
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = { "/useUp" }, produces = "application/json",method = { org.springframework.web.bind.annotation.RequestMethod.GET,
			org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
    public JsonResp<String> useUp(HttpServletRequest request, @RequestBody OpenReq openReq){
		PreparationInventoryDto preparationInventoryDto = null;
		ReagentInventoryDto reagentInventoryDto = null;
		// 判断编码非空
		if(StringUtils.isEmpty(openReq.getBarCode())){
			return new JsonResp<String>(SystemEnum.ARGUMENT_ERROR.getErrCode(),"条形码"+SystemEnum.ARGUMENT_ERROR.getErrChineseMsg());
		}
		
		// 判断用户id非空
		if(StringUtils.isEmpty(openReq.getUserId())){
			return new JsonResp<String>(SystemEnum.ARGUMENT_ERROR.getErrCode(),"用户id"+SystemEnum.ARGUMENT_ERROR.getErrChineseMsg());
		}
		
		LoginUser user = this.systemUserService.queryUserByUserId(openReq.getUserId());
		if(user != null){
			request.getSession().setAttribute("OPERATE_WEB_LOGIN_USER", user);
		}
		if(openReq.getBarCode().startsWith("01")){
			// 查询试剂
			reagentInventoryDto = this.reagentInventoryService.queryByNo(openReq.getBarCode());
			if(reagentInventoryDto == null){
				log.error("使用完毕操作失败，试剂编号："+openReq.getBarCode()+"，试剂库存表" + SystemEnum.DATA_NOT_EXIST_ERROR.getErrChineseMsg());
				return new JsonResp<String>(SystemEnum.OPERATION_ERROR.getErrCode(),SystemEnum.OPERATION_ERROR.getErrChineseMsg());
			}
			reagentInventoryDto.setStatus("2");
			reagentInventoryDto.setUpdateTime(new Date());
			reagentInventoryDto.setUpdateUser(user.getId().toString());
			reagentInventoryService.doEdit(reagentInventoryDto);
		}else if(openReq.getBarCode().startsWith("02")){
			// 查询试液
			preparationInventoryDto = this.preparationInventoryService.queryByNo(openReq.getBarCode());
			if(preparationInventoryDto == null){
				log.error("使用完毕操作失败，试液编号："+openReq.getBarCode()+"，试液库存表" + SystemEnum.DATA_NOT_EXIST_ERROR.getErrChineseMsg());
				return new JsonResp<String>(SystemEnum.OPERATION_ERROR.getErrCode(),SystemEnum.OPERATION_ERROR.getErrChineseMsg());
			}
			preparationInventoryDto.setStatus("2");
			preparationInventoryDto.setUpdateTime(new Date());
			preparationInventoryDto.setUpdateUser(user.getId().toString());
			preparationInventoryService.doEdit(preparationInventoryDto);
		}
		
        return new JsonResp<String>();
    }
	
	/**
	 * 试液试剂 丢弃
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = { "/abandon" }, produces = "application/json",method = { org.springframework.web.bind.annotation.RequestMethod.GET,
			org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
    public JsonResp<String> abandon(HttpServletRequest request, @RequestBody OpenReq openReq){
		PreparationInventoryDto preparationInventoryDto = null;
		ReagentInventoryDto reagentInventoryDto = null;
		// 判断编码非空
		if(StringUtils.isEmpty(openReq.getBarCode())){
			return new JsonResp<String>(SystemEnum.ARGUMENT_ERROR.getErrCode(),"条形码"+SystemEnum.ARGUMENT_ERROR.getErrChineseMsg());
		}
		
		// 判断用户id非空
		if(StringUtils.isEmpty(openReq.getUserId())){
			return new JsonResp<String>(SystemEnum.ARGUMENT_ERROR.getErrCode(),"用户id"+SystemEnum.ARGUMENT_ERROR.getErrChineseMsg());
		}
		
		LoginUser user = this.systemUserService.queryUserByUserId(openReq.getUserId());
		if(user != null){
			request.getSession().setAttribute("OPERATE_WEB_LOGIN_USER", user);
		}
		if(openReq.getBarCode().startsWith("01")){
			// 查询试剂
			reagentInventoryDto = this.reagentInventoryService.queryByNo(openReq.getBarCode());
			if(reagentInventoryDto == null){
				log.error("丢弃操作失败，试剂编号："+openReq.getBarCode()+"，试剂库存表" + SystemEnum.DATA_NOT_EXIST_ERROR.getErrChineseMsg());
				return new JsonResp<String>(SystemEnum.OPERATION_ERROR.getErrCode(),SystemEnum.OPERATION_ERROR.getErrChineseMsg());
			}
			reagentInventoryDto.setStatus("3");
			reagentInventoryDto.setUpdateTime(new Date());
			reagentInventoryDto.setUpdateUser(user.getId().toString());
			reagentInventoryService.doEdit(reagentInventoryDto);
		}else if(openReq.getBarCode().startsWith("02")){
			// 查询试液
			preparationInventoryDto = this.preparationInventoryService.queryByNo(openReq.getBarCode());
			if(preparationInventoryDto == null){
				log.error("丢弃操作失败，试液编号："+openReq.getBarCode()+"，试液库存表" + SystemEnum.DATA_NOT_EXIST_ERROR.getErrChineseMsg());
				return new JsonResp<String>(SystemEnum.OPERATION_ERROR.getErrCode(),SystemEnum.OPERATION_ERROR.getErrChineseMsg());
			}
			preparationInventoryDto.setStatus("3");
			preparationInventoryDto.setUpdateTime(new Date());
			preparationInventoryDto.setUpdateUser(user.getId().toString());
			preparationInventoryService.doEdit(preparationInventoryDto);
		}
		
        return new JsonResp<String>();
    }
	
	/**
	 * 配制试液
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = { "/generate" }, produces = "application/json",method = { org.springframework.web.bind.annotation.RequestMethod.GET,
			org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
    public JsonResp<PreparationInventoryDto> generate(HttpServletRequest request, @RequestBody PreparationInventoryDto preparationInventory){
		
		LoginUser user = this.systemUserService.queryUserByUserId(preparationInventory.getUserId());
		if(user != null){
			request.getSession().setAttribute("OPERATE_WEB_LOGIN_USER", user);
		}
		
		JsonResp<PreparationInventoryDto> jsonResp = new JsonResp<PreparationInventoryDto>();
		// 判断配制日期非空
		if(StringUtils.isEmpty(preparationInventory.getConfigurationDate())){
			return new JsonResp<PreparationInventoryDto>(SystemEnum.ARGUMENT_ERROR.getErrCode(),"配制日期"+SystemEnum.ARGUMENT_ERROR.getErrChineseMsg());
		}
		
		// 判断有效日期非空
		if(StringUtils.isEmpty(preparationInventory.getEffectiveDate())){
			return new JsonResp<PreparationInventoryDto>(SystemEnum.ARGUMENT_ERROR.getErrCode(),"有效日期"+SystemEnum.ARGUMENT_ERROR.getErrChineseMsg());
		}
		
		// 判断试液类型非空
		if(preparationInventory.getPreparationTypeId()==null){
			return new JsonResp<PreparationInventoryDto>(SystemEnum.ARGUMENT_ERROR.getErrCode(),"试液类型"+SystemEnum.ARGUMENT_ERROR.getErrChineseMsg());
		}
		
		// 判断配制人非空
		if(preparationInventory.getUserId()==null){
			return new JsonResp<PreparationInventoryDto>(SystemEnum.ARGUMENT_ERROR.getErrCode(),"配制人"+SystemEnum.ARGUMENT_ERROR.getErrChineseMsg());
		}
		
		// 编号规则 01:试剂 02：试液
		String type = "02";
		String year = DateUtils.formatString(new Date(), "yyyyMMdd");
		// 查询db中的最大编号
		int maxNo = preparationInventoryService.getMaxNo(type+year);
		maxNo++;
		String barCode = type+year+String.format("%04d", maxNo);
		preparationInventory.setPrintStatus("0");
		preparationInventory.setBarCode(barCode);
		preparationInventory.setStatus("1");
		preparationInventory.setCreateUser(user.getId().toString());
		preparationInventory.setCreateTime(new Date());
		preparationInventory.setUpdateUser(user.getId().toString());
		preparationInventory.setUpdateTime(new Date());
		preparationInventory.setPreparationType(preparationTypeService.queryById(preparationInventory.getPreparationTypeId().toString()).getName());
		
		preparationInventoryService.doAdd(preparationInventory);
		
		jsonResp.setInfo(preparationInventory);
        return jsonResp;
    }
	
	
	@RequestMapping(value = { "/printBarCodeInfo" }, produces = "application/json",method = { org.springframework.web.bind.annotation.RequestMethod.GET,
			org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
    public JsonResp<String> printBarCodeInfo(@RequestBody BarCodeReq barCodeDto) throws IOException{
		if(barCodeDto.getBarCode().startsWith("02")){
			// 设置打印标记为未打印
			this.preparationInventoryService.startPrint(barCodeDto.getBarCode());
		}else{
			// 设置打印标记为未打印
			this.reagentInventoryService.startPrint(barCodeDto.getBarCode());
		}
		
		return new JsonResp<String>();
    }
	
}
